<template>
  <el-dialog v-model="upholdVisible" :destroy-on-close="true" title="新建资产信息" width="500" class="dialog-box">
    <div class="uphold-operation">
      <el-form ref="modalFormRef" :model="modalForm" label-width="auto" :rules="modalFormRule">
        <el-form-item label="维护信息：" prop="content">
          <el-input type="textarea" v-model="modalForm.content" placeholder="请输入维护记录" />
        </el-form-item>
        <el-form-item label="上传附件：" prop="desc">
          <div class="file-block">
            <el-upload
              v-model:file-list="fileList"
              ref="uploadRef"
              class="upload-demo"
              action="#"
              multiple
              :http-request="handleHttpUpload"
              :limit="limit"
              :on-exceed="handleExceed"
              :on-success="uploadSuccess"
              accept=".doc,.docx,.jpg,.png,.ppt,.pptx,.pdf"
            >
              <el-button type="primary" :icon="Upload">点击上传</el-button>
              <template #tip>
                <div class="el-upload__tip">支持PDF、DOC、PPT、JPG、PNG格式，最多上传10个文件。</div>
              </template>
              <template #file="{ file }">
                <div class="file-box" v-if="file.url">
                  <a :href="file.url" target="_blank" :title="file.name">
                    <el-icon><Link /></el-icon>{{ file.name }}
                  </a>
                  <div class="handle-icon">
                    <el-icon @click.stop="handleRemove(file)"><Close /></el-icon>
                  </div>
                </div>
              </template>
            </el-upload>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submit(modalFormRef)" :loading="loading">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="uphold">
import { createUphold } from "@/api/modules/asset";
import { ref } from "vue";
import { ElMessage, FormInstance, type UploadFile } from "element-plus";
import { Upload } from "@element-plus/icons-vue";
import type { UploadProps, UploadUserFile, UploadRequestOptions } from "element-plus";
import { uploadFile } from "@/api/modules/asset";

const props = defineProps({
  data: {
    type: Object,
    required: false,
    default: () => ({})
  }
});
// emit
const emit = defineEmits<{
  refresh: [];
}>();
const modalForm = ref<any>({
  content: "",
  file_links: []
});
const upholdVisible = ref<boolean>(false);
const modalFormRule = ref<any>({
  content: [
    { required: true, message: "内容不能为空", trigger: "blur" },
    { min: 1, max: 128, message: "1~128个字符(128为最大支持数量)", trigger: "blur" }
  ]
});
const fileList = ref<UploadUserFile[]>([]);
const loading = ref<boolean>(false);
const modalFormRef = ref<FormInstance>();
const submit = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async val => {
    if (val) {
      loading.value = true;
      await createUphold(props.data.id, modalForm.value);
      ElMessage.success("维护操作成功");
      loading.value = false;
      closeDialog();
      emit("refresh");
    }
  });
};
// 上传文件
const limit = ref<number>(10);
const handleExceed: UploadProps["onExceed"] = () => {
  ElMessage.warning(`最多上传${limit.value}个文件`);
};
const uploadSuccess = (response: { link: string } | undefined, uploadFile: UploadFile) => {
  if (!response) return;
  uploadFile.url = response.link;
  modalForm.value["file_links"].push(response);
  ElMessage.success(`上传成功`);
};
const handleRemove = (file: UploadFile) => {
  fileList.value = fileList.value.filter(item => item.url !== file.url || item.name !== file.name);
  modalForm.value["file_links"] = modalForm.value["file_links"].filter(item => item.link !== file.url);
};
/**
 * @description 文件上传
 * @param options upload 所有配置项
 * */
const uploadRef = ref(null);
const handleHttpUpload = async (options: UploadRequestOptions) => {
  const allowedFileTypes = [
    "image/jpeg", // JPEG 图像文件
    "image/png", // PNG 图像文件
    "application/msword", // Microsoft Word 文档
    "application/pdf", //pdf
    "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    "application/vnd.openxmlformats-officedocument.presentationml.presentation" // ppt
  ];
  // 获取文件的类型
  const fileType = options.file.type;
  // console.log(file.file.type, '上传的附件');
  if (!allowedFileTypes.includes(fileType)) {
    ElMessage({
      type: "error",
      message: "上传格式错误"
    });
    return false; // 阻止文件上传
  } else {
    let formData = new FormData();
    formData.append("file", options.file);
    try {
      const { data } = await uploadFile(formData);
      options.onSuccess(data);
    } catch (error) {
      options.onError(error as any);
    }
  }
};
const openDialog = () => {
  upholdVisible.value = true;
  modalForm.value.content = "";
  modalForm.value.file_links = [];
  fileList.value = [];
};
const closeDialog = () => {
  upholdVisible.value = false;
};
defineExpose({
  openDialog,
  closeDialog
});
</script>

<style lang="scss" scoped>
.file-box {
  display: flex;
  align-items: center;
  a {
    width: 310px;
    overflow: hidden; /* 隐藏超出部分 */
    text-overflow: ellipsis;
    white-space: nowrap; /* 不换行 */
    .el-icon {
      position: relative;
      top: 2px;
      margin-right: 8px;
    }
  }
  .handle-icon {
    flex: auto;
    text-align: right;
    .el-icon {
      position: relative;
      top: 2px;
      cursor: pointer;
    }
  }
}
:deep(.el-upload-list__item) {
  margin-bottom: 0;
}
</style>
